//
//  SwipeViewController.m
//  MagTek.iDynamo.ObjC
//
//  Created by agharris73 on 9/18/13.
//  Copyright (c) 2013 Mercury. All rights reserved.
//

#import "SwipeViewController.h"
#import "MTSCRA.h"
#import "SwipeInitResultsViewController.h"
#import "general data.h"
#import "DataBaseManager.h"
static MTSCRA *magTek = nil;
@interface SwipeViewController ()

@property (nonatomic, weak) IBOutlet UIImageView *ccSwipe;
//    @property (strong, nonatomic) MTSCRA *magTek;
@end

@implementation SwipeViewController
{
//    EncryptedSwipeData *encryptedSwipeData;
    general_data *generalDataObject;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	if (!magTek) {
        magTek = [[MTSCRA alloc] init];
        [magTek listenForEvents:(TRANS_EVENT_OK|TRANS_EVENT_START|TRANS_EVENT_ERROR)];
        [magTek setDeviceProtocolString:(@"com.magtek.idynamo")];
    }
    self.amount.text=self.merchantInfo.purchase;
    ////NSLog(@"%@",self.merchantInfo.purchase);
    
   generalDataObject=[general_data new];
    [generalDataObject GetuserDataVariablesMethod];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _paymentBtn.enabled = YES;
    
}
//- (IBAction)simSwipeuDynamoButtonPressed:(id)sender {
//    [self.simSwipeuDynamoSwitch setOn:!self.simSwipeuDynamoSwitch.on animated:true];
//    [self magTek_deactivate];
//    
//    if (self.simSwipeuDynamoSwitch.on) {
//        [self magtek_activateWithDeviceType:MAGTEKAUDIOREADER];
//    }
//}
//
//- (IBAction)simSwipeduDynamoSwitchFlipped:(id)sender {
//    [self magTek_deactivate];
//    
//    if (self.simSwipeuDynamoSwitch.on) {
//        [self magtek_activateWithDeviceType:MAGTEKAUDIOREADER];
//    }
//}

//-----------------------------------------------------------------------------
#pragma mark - MagTek SDK activation/deactivation -
//-----------------------------------------------------------------------------
- (IBAction)SwipetheCardButtonClick:(id)sender
{
    [self.merchantInfo cleanSwipeData];
    _statusMsg.text = @"initializing device";
    _statusMsg.textColor = [UIColor yellowColor];
    UIButton *ref = (UIButton *)sender;
    ref.enabled = NO;
    switch (_paymentType.selectedSegmentIndex) {
        case 0:
            self.merchantInfo.tranType = @"Credit";
            break;
        case 1:
            self.merchantInfo.tranType = @"PrePaid";
            break;
        default:
            break;
    }
    
    NSString *querySQL = [NSString stringWithFormat: @"SELECT merchant_name,merchant_address,merchant_zipcode,server_local,merchant_address2,merchant_phone FROM merchant_info_table"];
    NSMutableArray *merchantDataArray=[[NSMutableArray alloc]init];
    [[DataBaseManager dataBaseManager]execute:querySQL resultsArray:merchantDataArray];
    
    NSString *merchnatname,*address1,*address2,*phno,*zipcode;
    if ([merchantDataArray count]>0)
    {
        NSDictionary *Dict=[merchantDataArray objectAtIndex:0];
        merchnatname=[Dict objectForKey:@"merchant_name"];
        address1=[Dict objectForKey:@"merchant_address"];
        address2=[Dict objectForKey:@"merchant_address2"];
        phno=[Dict objectForKey:@"merchant_phone"];
        zipcode=[Dict objectForKey:@"merchant_zipcode"];
        Dict=Nil;
    }
   // NSLog(@"invoice no%@",self.invoiceNo);
    
    self.merchantInfo.zip=zipcode;
    self.merchantInfo.address=address1;
    self.merchantInfo.name=merchnatname;
    self.merchantInfo.tranCode = @"Sale";
    self.merchantInfo.invoiceNo =self.invoiceNo;
    self.merchantInfo.refNo = @"12345";
    self.merchantInfo.memo = @"A One Pos 3.0";
    self.merchantInfo.partialAuth = @"Allow";
    self.merchantInfo.encryptedFormat = @"MagneSafe";
    self.merchantInfo.accountSource = @"Swiped";
    self.merchantInfo.frequency = @"OneTime";
    self.merchantInfo.recordNo = @"RecordNumberRequested";
    self.merchantInfo.purchase = _amount.text;
    //self.merchantInfo.name = @"test";
    self.merchantInfo.terminalName = @"MPS Terminal";
    self.merchantInfo.shiftID = @"MPS Shift";
    self.merchantInfo.operatorID =[generalDataObject userID];
    //self.merchantInfo.address =@"4 Corporate SQ";
    //self.merchantInfo.zip = @"30329";
    
    
    [self magTek_deactivate];
    
    [self magtek_activateWithDeviceType:MAGTEKAUDIOREADER];
    [merchantDataArray removeAllObjects];
}
- (void)magtek_activateWithDeviceType:(UInt32)deviceType
{
    [magTek setDeviceType:deviceType];
    [magTek openDevice];
    [self magtek_registerObservers:true];
    [self displayDeviceStatus];
}

-(void)magTek_deactivate {
    [self magtek_registerObservers:false];
    [self disconnected];
    
    if (magTek != NULL && magTek.isDeviceOpened)
    {
        [magTek closeDevice];
    }
    
}

//-----------------------------------------------------------------------------
#pragma mark - MagTek SDK observers -
//-----------------------------------------------------------------------------

- (void)magtek_registerObservers:(BOOL) reg {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
  //  //NSLog(@"tarck data %@",nc);
    if (reg) {
        [nc addObserver:self selector:@selector(trackDataReady:) name:@"trackDataReadyNotification" object:nil];
        [nc addObserver:self selector:@selector(devConnStatusChange) name:@"devConnectionNotification" object:nil];
    }
    else {
        [nc removeObserver:self];
    }
}


- (void)trackDataReady:(NSNotification *)notification
{
    NSNumber *status = [[notification userInfo] valueForKey:@"status"];
    
    [self performSelectorOnMainThread:@selector(onDataEvent:)
                           withObject:status
                        waitUntilDone:NO];
}

- (void)onDataEvent:(id)status
{
    switch ([status intValue]) {
        case TRANS_STATUS_OK:
            //NSLog(@"TRANS_STATUS_OK");
            self.merchantInfo.track1Masked = [[NSString alloc]initWithString:magTek.getTrack1Masked];
            self.merchantInfo.track2Masked = [[NSString alloc]initWithString:magTek.getTrack2Masked];
            self.merchantInfo.track1Encrypted = [[NSString alloc]initWithString:magTek.getTrack1];
            self.merchantInfo.track2Encrypted = [[NSString alloc]initWithString:magTek.getTrack2];
            self.merchantInfo.ksn = [[NSString alloc]initWithString:magTek.getKSN];
            [self determineNextStep];
            break;
        case TRANS_STATUS_ERROR:
//            //NSLog(@"TRANS_STATUS_ERROR");
            break;
        default:
            break;
    }
}

- (void)devConnStatusChange
{
    [self displayDeviceStatus];
}

#pragma mark connection task

//-----------------------------------------------------------------------------
#pragma mark - Methods -
//-----------------------------------------------------------------------------

- (IBAction)disconnected {
    _statusMsg.text = @"device disconnected";
    _statusMsg.textColor = [UIColor redColor];
    _paymentBtn.enabled = YES;
    self.imageCardState.image = [UIImage imageNamed:@"ccStaticState.png"];
    CATransition *transition = [CATransition animation];
    transition.type = kCATransitionFade; // there are other types but this is the nicest
    transition.duration = 0.34; // set the duration that you like
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [self.imageCardState.layer addAnimation:transition forKey:nil];
}

- (IBAction)connected {
    _statusMsg.text = @"device connected, ready to swipe...";
    _statusMsg.textColor = [UIColor greenColor];
    _paymentBtn.enabled = NO;
    self.imageCardState.image = [UIImage imageNamed:@"ccSwipeState.png"];
    CATransition *transition = [CATransition animation];
    transition.type = kCATransitionFade; // there are other types but this is the nicest
    transition.duration = 0.34; // set the duration that you like
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [self.imageCardState.layer addAnimation:transition forKey:nil];
}

- (void)displayDeviceStatus
{
    BOOL isMagTekDeviceConnected = [magTek isDeviceConnected];
    BOOL isMagTekDeviceOpen = [magTek isDeviceOpened];
    
    if ((magTek && isMagTekDeviceConnected && isMagTekDeviceOpen)){
        [self connected];
    }
    else {
        [self disconnected];
    }
}

- (int) encryptedLengthFromMasked: (int)maskedLength {
    int value = maskedLength;
    
    if (value > 0) {
        value = abs(8-(maskedLength % 8)) + maskedLength;
    }
    
    return value;
}

- (NSString*) hexFromData:(NSData*) data
{
    const unsigned char *dataBuffer = (const unsigned char *)[data bytes];
    
    if (!dataBuffer) {
        return [NSString string];
    }
    
    NSUInteger dataLength  = data.length;
    NSMutableString *hexString  = [NSMutableString stringWithCapacity:(dataLength * 2)];
    
    for (int i = 0; i < dataLength; ++i) {
        [hexString appendString:[NSString stringWithFormat:@"%02x", (unsigned int)dataBuffer[i]]];
    }
    
    return [NSString stringWithString:hexString];
}

- (void)determineNextStep {
    
    [self magTek_deactivate];
    
    if (self.merchantInfo.track2Masked != nil
        && [self.merchantInfo.track2Masked rangeOfString:@"="].location != NSNotFound)
    {
        self.merchantInfo.encryptedBlock = self.merchantInfo.track2Encrypted;
        self.merchantInfo.encryptedKey = self.merchantInfo.ksn;

        SwipeInitResultsViewController *swipeInitResultViewController=[[SwipeInitResultsViewController alloc]initWithNibName:@"SwipeInitResultsViewController" bundle:nil];
        swipeInitResultViewController.paymentInfo=self.merchantInfo;
        [self.navigationController pushViewController:swipeInitResultViewController animated:NO];
        [self releaseViews];
    }
    else if(self.paymentBtn.enabled) {
        [self magtek_activateWithDeviceType: MAGTEKAUDIOREADER];
    }
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"segueSwipeResults"]) {
        //SwipeInitResultsViewController *target = (SwipeInitResultsViewController *)segue.destinationViewController;
       // target.paymentInfo = self.merchantInfo;
    }
    
}
- (IBAction)prepareForPayment:(id)sender {
    [self.merchantInfo cleanSwipeData];
    _statusMsg.text = @"initializing device";
    _statusMsg.textColor = [UIColor yellowColor];
    UIButton *ref = (UIButton *)sender;
    ref.enabled = NO;
    switch (_paymentType.selectedSegmentIndex) {
        case 0:
            self.merchantInfo.tranType = @"Credit";
            break;
        case 1:
            self.merchantInfo.tranType = @"PrePaid";
            break;
        default:
            break;
    }
    
    NSString *querySQL = [NSString stringWithFormat: @"SELECT merchant_name,merchant_address,merchant_zipcode,server_local,merchant_address2,merchant_phone FROM merchant_info_table"];
    NSMutableArray *merchantDataArray=[[NSMutableArray alloc]init];
    [[DataBaseManager dataBaseManager]execute:querySQL resultsArray:merchantDataArray];
    
    NSString *merchnatname,*address1,*address2,*phno,*zipcode;
    if ([merchantDataArray count]>0)
    {
        NSDictionary *Dict=[merchantDataArray objectAtIndex:0];
        merchnatname=[Dict objectForKey:@"merchant_name"];
        address1=[Dict objectForKey:@"merchant_address"];
        address2=[Dict objectForKey:@"merchant_address2"];
        phno=[Dict objectForKey:@"merchant_phone"];
        zipcode=[Dict objectForKey:@"merchant_zipcode"];
        Dict=Nil;
    }
    self.merchantInfo.zip=zipcode;
    self.merchantInfo.address=address1;
    self.merchantInfo.name=merchnatname;
    self.merchantInfo.tranCode = @"Sale";
    self.merchantInfo.invoiceNo =self.invoiceNo;
    self.merchantInfo.refNo = @"12345";
    self.merchantInfo.memo = @"A One Pos 3.0";
    self.merchantInfo.partialAuth = @"Allow";
    self.merchantInfo.encryptedFormat = @"MagneSafe";
    self.merchantInfo.accountSource = @"Swiped";
    self.merchantInfo.frequency = @"OneTime";
    self.merchantInfo.recordNo = @"RecordNumberRequested";
    self.merchantInfo.purchase = _amount.text;
    //self.merchantInfo.name = @"test";
    self.merchantInfo.terminalName = @"MPS Terminal";
    self.merchantInfo.shiftID = @"MPS Shift";
    self.merchantInfo.operatorID =[generalDataObject userID];
    //self.merchantInfo.address =@"4 Corporate SQ";
    //self.merchantInfo.zip = @"30329";
    
    
    [self magTek_deactivate];
    
    [self magtek_activateWithDeviceType:MAGTEKAUDIOREADER];
    [merchantDataArray removeAllObjects];
    
}
-(void)releaseViews
{
    [_imageCardState  removeFromSuperview];
    _imageCardState=nil;
    [_paymentBtn  removeFromSuperview];
    _paymentBtn=nil;
    [_amount  removeFromSuperview];
    _amount=nil;
    [_statusMsg  removeFromSuperview];
    _statusMsg=nil;
    [_paymentType  removeFromSuperview];
    _paymentType=nil;
    _merchantInfo=nil;
    _invoiceNo=nil;
    
}
- (IBAction)backButtonClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
    [self releaseViews];
}
@end
